package controllers

import (
	"context"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"path/filepath"
	"strconv"
	"strings"
	"video/models"
	"video/util"
)

var ctx = context.Background()

type VideoController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *VideoController) Add() {
	title := c.GetString("title")
	author := c.GetString("author")
	zan, _ := c.GetInt("zan")
	cate := c.GetString("cate")
	img := c.GetString("img")
	if !util.IsValidChinese(author) {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "作者格式不正确，要求2-4个中文汉字",
			Data: nil,
		}
		c.ServeJSON()
	}
	video := models.Video{
		Title:  title,
		Author: author,
		Zan:    zan,
		Cate:   cate,
		Img:    img,
	}
	err := models.VideoCreate(&video)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		//fmt.Println("插入的ID为", video.ID)
		key := "video-" + strconv.Itoa(int(video.ID))
		jsonByte, _ := json.Marshal(video)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}

// 分页

func (c *VideoController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 5)
	title := c.GetString("title")
	key := "page-" + strconv.Itoa(page) + "-" + strconv.Itoa(pageSize) + "-" + title //page-1-10  page-2-5
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		videos, total, err := models.VideoPage(page, pageSize, title)
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "查询失败",
				Data: nil,
			}
			c.ServeJSON()
		}
		pageData["videos"] = videos
		pageData["total"] = total
		jsonByte, _ := json.Marshal(pageData)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageData)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "查询成功-redis",
			Data: pageData,
		}
		c.ServeJSON()
	}

}

// 先判断redis缓存中有没有数据，有的话直接读取redis，如果缓存中没有数据，读取mysql,存入缓存中

func (c *VideoController) Show() {
	// 浏览量加入缓存
	id, _ := c.GetInt("id")
	bankName := "video-rank" //key
	number := strconv.Itoa(id)
	models.Rdb.ZIncrBy(bankName, 1, number)
	key := "video-" + strconv.Itoa(id) // video-1  video-2  video-100
	var video models.Video
	val, err := models.Rdb.Get(key).Result() //获取缓存，如果缓冲中有数据的话，直接返回缓存中数据，没有的话读取数据库，并且加入缓存
	if err != nil {
		err = models.DB.Model(&video).Where("id = ?", id).First(&video).Error
		if err != nil {
			c.Data["json"] = JsonRes{
				Code: 500,
				Msg:  "展示失败",
				Data: val,
			}
			c.ServeJSON()
		}
		jsonByte, _ := json.Marshal(video) // 转化为json格式字符串
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: video,
		}
		c.ServeJSON()

	} else {
		json.Unmarshal([]byte(val), &video)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: video,
		}
		c.ServeJSON()
	}
	/*   没加缓存之前的代码
	var video models.Video
	err := models.DB.Model(&video).Where("id = ?", id).First(&video).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "展示成功",
			Data: video,
		}
		c.ServeJSON()
	}
	*/
}

func (c *VideoController) Delete() {
	id, _ := c.GetInt("id")
	key := "video-" + strconv.Itoa(id)
	err := models.DB.Delete(&models.Video{}, id).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		models.Rdb.Del(key)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *VideoController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件获取失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close() //关闭文件
	// 文件大小不能超过   （字节）
	if header.Size > 2*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件过大请重新上传",
			Data: nil,
		}
		c.ServeJSON()
	}
	// 文件格式验证  .png  .jpeg .jpg
	// su7.jpeg
	suffix := strings.ToLower(filepath.Ext(header.Filename)) //获取文件后缀（转化为了小写）
	suffixMap := map[string]bool{
		".PNG":  true,
		".jpeg": true,
		".jpg":  true,
	}
	if !suffixMap[suffix] {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "格式错误，只支持png,jpeg,jpg格式",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		imgSrc := "http://localhost:8080/" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "上传成功",
			Data: imgSrc,
		}
		c.ServeJSON()
	}
}

func (c *VideoController) FileUpload() {
	uploader := util.NewUploader(2*1024*1024, []string{".png", ".jpeg", ".jpg"})
	uploader.Upload(&c.Controller, "img", "static/img")
}

func (c *VideoController) Update() {
	title := c.GetString("title")
	author := c.GetString("author")
	zan, _ := c.GetInt("zan")
	cate := c.GetString("cate")
	img := c.GetString("img")
	id, _ := c.GetInt("id")
	video := models.Video{
		Model:  gorm.Model{ID: uint(id)},
		Title:  title,
		Author: author,
		Zan:    zan,
		Cate:   cate,
		Img:    img,
	}
	err := models.DB.Updates(&video).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		key := "video-" + strconv.Itoa(id)
		jsonByte, _ := json.Marshal(&video)
		models.Rdb.Set(key, string(jsonByte), 0)
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "修改成功",
			Data: nil,
		}
		c.ServeJSON()
	}

}

// 排行榜

func (c *VideoController) VideoRank() {
	// 获取有序集合的元素（前10名）
	result, err := models.Rdb.ZRevRange("video-rank", 0, 9).Result()
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "展示失败",
		}
		c.ServeJSON()
		return
	}
	var rankSlice []models.Video
	for _, number := range result {
		var video models.Video
		models.DB.Model(&models.Video{}).Where("ID = ?", number).First(&video)
		rankSlice = append(rankSlice, video)
	}
	c.Data["json"] = JsonRes{
		Code: 200,
		Msg:  "展示成功",
		Data: rankSlice,
	}
	c.ServeJSON()
}
